var lm = false, lastTrPublicId, rowBgColors = new Array('#FFF2E9', '#FBE3C9');

gid = function(id) {return document.getElementById(id);}

function change_language(i)
{
	//http://www.growmetry.com/APX_Translate/main_menu.asp
	//var str_domain = "www.growmetry.com"
	//var str_pathname = window.location.pathname;
	//var str_ziel = str_domain && str_pathname;
	
	
	var str_ziel = new String(window.location);
	
	var p1 = get_page_params();
	var p2 = get_page_params();
	
	var i_language ="0";//default - 0=bedeutet ohne lng=x // 1=mit lng=x zb. .asp?lng=1
	var i_asp="0";//default -1=bedeutet das in der url zum schluss nur mehr asp steht // 0=das in der url schon zus?tzliche parameter stehen zb: .asp?btnsub=N oder .asp?lng=1
	
	//?berpr?ft ob schon ein sprachinfo in der url ist
	  if (p2['lng']) 
	  {
	  	//Do something
	  	i_language = 1
		//alert("NNNN");
	  }  
	  else
	  {
	  	i_language = 0   
	  }


	//?berpr?ft ob es eine info in der URL gibt
	  var str_asp_default = "asp";
	  //var i_laenge = str_ziel.length;
	  //var str_last03 = new String((str_ziel[i_laenge-3] + str_ziel[i_laenge-2] + str_ziel[i_laenge-1]));
	  var str_last03 = str_ziel.substr((str_ziel.length)-3); //liefert die letzten drei zeichen
	  
	  if (str_last03 == str_asp_default)//german
	  {
		//default 1=bedeutet das in der url zum schluss nur mehr asp steht
		i_asp = 1;
	  }
	  else
	  {
		//default 0=das in der url schon zus?tzliche parameter stehen zb: .asp?btnsub=N oder .asp?lng=1
		i_asp = 0;
	  }
	  

	//alert("str_ziel: " + str_ziel);
	//alert("str_last03: " + str_last03);
	//alert("i: " + i);
	//alert("i_language: " + i_language);	  
	//alert("i_asp: " + i_asp);
	
	//wenn in der url noch keine parameter sind und die sprachinfo auch fehlt
	  if (i_asp == "1" && i=="1" && i_language=="0")//german
	  {
			str_ziel = str_ziel + "?lng=1"  
	  }
	  if (i_asp == "1" && i=="2" && i_language=="0")//english
	  {
			str_ziel = str_ziel + "?lng=2"  
	  }

	//wenn in der url schon parameter sind und die sprachinfo auch fehlt
	  if (i_asp == "0" && i=="1" && i_language=="0")//german
	  {
			str_ziel = str_ziel + "&lng=1"  
	  }
	  if (i_asp == "0" && i=="2" && i_language=="0")//english
	  {
			str_ziel = str_ziel + "&lng=2"  
	  }

	//wird nur ausgef?hrt wenn schon eine sprachinfo in der url ist
	  if (i == "1")//german
	  {
		  str_ziel = SuchenUndErsetzen(str_ziel, "lng=2", "lng=1")
	  } 
	  
	  if (i == "2")//English
	  {
		  str_ziel = SuchenUndErsetzen(str_ziel, "lng=1", "lng=2")
	  } 


	window.location.href = str_ziel;
}

function SuchenUndErsetzen(QuellText, SuchText, ErsatzText)
{   // Erstellt von Ralf Pfeifer
	  // Fehlerpruefung
	  if ((QuellText == null) || (SuchText == null))           {return null;}
	  if ((QuellText.length == 0) || (SuchText.length == 0))   {return QuellText;}

	  // Kein ErsatzText ?
	  if ((ErsatzText == null) || (ErsatzText.length == 0))    {ErsatzText = "";}

	  var LaengeSuchText = SuchText.length;
	  var LaengeErsatzText = ErsatzText.length;
	  var Pos = QuellText.indexOf(SuchText, 0);

	  while (Pos >= 0)
	  {
		  QuellText = QuellText.substring(0, Pos) + ErsatzText + QuellText.substring(Pos + LaengeSuchText);
		  Pos = QuellText.indexOf(SuchText, Pos + LaengeErsatzText);
	  }
	  return QuellText;
}


//sucht einen String innerhalb eines Strings (Andrey)
function get_page_params() 
{
       function unspace( qs_element ) {
               return qs_element.split( '+' ).join( ' ' );
       }
       var QueryString = new Array();
       QueryString["_"]="";
       if ( location.search.length > 1 ) {
               var qs_query = location.search.substring( 1, location.search.length );
               var qs_pairs = qs_query.split( '&' );
               for ( var qs_index = 0; qs_index < qs_pairs.length; qs_index++ ) {
                       var qs_element = qs_pairs[qs_index].split( '=' );
                       QueryString[qs_element[0]] = unspace( unescape( qs_element[1] ) );
               }
       }
       return QueryString;

}

function go_back(i)
{
    var go_back_01 = "main_menu.asp";
    location.href=go_back_01;
}

window.onload = function(){
    loadInitialData();
}

function closeLoadingModal(){
    if ( lm ) {
        lm.close();
        lm = false;
    }
}

function showLoadingModal(){
    closeLoadingModal();
    lm = $('#loading_wait').modal({opacity:30, escClose: false});
}

function loadInitialData() {
    if ( userGroup == 1 || userGroup == 2 ) {
        loadDivisions();
    } else if ( userGroup == 3 ) {
        document.getElementById('rep-divisions-env').className = "";
    	document.getElementById('rep-divisions-env').style.display = "";
    	document.getElementById('rep-divisions').style.display = "none";
    	document.getElementById('rep-divisions-showall').style.display = "none";
        loadTrainers();
    } else if ( userGroup == 4 ) {
        document.getElementById('rep-divisions-env').className = "";
        document.getElementById('rep-trainers-env').className = "";
    	document.getElementById('rep-divisions-env').style.display = "";
    	document.getElementById('rep-divisions').style.display = "none";
    	document.getElementById('rep-divisions-showall').style.display = "none";
    	document.getElementById('rep-trainers-env').style.display = "";
    	document.getElementById('rep-trainers').style.display = "none";
    	document.getElementById('rep-trainers-showall').style.display = "none";
        loadAthletes();
    }
}

function loadDivisions(){
    showLoadingModal();
    var parms = "detail_level=divisions&public_key=" + asp_session_public_key;
    dhtmlxAjax.post("datasets/stat-divisions.php", parms, function(loader){
        if ( loader.xmlDoc.responseText.substr(0, 1) == '{' ) {
            var json = eval ("(" + loader.xmlDoc.responseText + ")");
            if ( json && typeof json === 'object' ) {
                showDivisions(json);
                closeLoadingModal();
            } else {
                closeLoadingModal();
                alert('Unknown request error occured');
            }
        } else {
            closeLoadingModal();
            alert('Error requesting the report data. Error: ' + loader.xmlDoc.responseText);
        }
    });
}

function loadTrainers(divTitle, divPublicId, divisionRowIdx){
    showLoadingModal();
    var parms = "detail_level=trainers&public_key=" + asp_session_public_key;
    if ( divPublicId ) {
        parms = parms + "&division=" + escape(divPublicId);
    }
    dhtmlxAjax.post("datasets/stat-divisions.php", parms, function(loader){
        if ( loader.xmlDoc.responseText.substr(0, 1) == '{' ) {
            var json = eval ("(" + loader.xmlDoc.responseText + ")");
            if ( json && typeof json === 'object' ) {
                document.getElementById('rep-athletes-env').style.display = "none";
                showTrainers(json);
                if ( userGroup < 3 ) {
                    toggleTableRows(document.getElementById('rep-divisions'), divisionRowIdx);
                }
                closeLoadingModal();
            } else {
                closeLoadingModal();
                alert('Unknown request error occured');
            }
        } else {
            closeLoadingModal();
            alert('Error requesting the report data. Error: ' + loader.xmlDoc.responseText);
        }
    });
}

function loadAthletes(trPublicId, refresh, trRowIdx){
    showLoadingModal();
    var parms = "detail_level=athletes&public_key=" + asp_session_public_key + "&filter=" + document.getElementById('athletes-filter-list').value;
    if ( trPublicId ) {
        lastTrPublicId = trPublicId;
        parms = parms + "&trainer=" + escape(trPublicId);
    }
    dhtmlxAjax.post("datasets/stat-divisions.php", parms, function(loader){
        if ( loader.xmlDoc.responseText.substr(0, 1) == '{' ) {
            var json = eval ("(" + loader.xmlDoc.responseText + ")");
            if ( json && typeof json === 'object' ) {
                showAthletes(json);
                if ( ! refresh && userGroup < 4 ) {
                    toggleTableRows(document.getElementById('rep-trainers'), trRowIdx);
                }
                closeLoadingModal();
            } else {
                closeLoadingModal();
                alert('Unknown request error occured');
            }
        } else {
            closeLoadingModal();
            alert('Error requesting the report data. Error: ' + loader.xmlDoc.responseText);
        }
    });
}

function showDivisions(json){
    var cellIdx, cell_classes = ['rep-table-title', 'rep-table-common', 'rep-table-involved', 'rep-table-avg-bio-age', 'rep-table-age-older', 'rep-table-age-older', 'rep-table-common',
        'rep-table-age-younger', 'rep-table-age-younger', 'rep-table-common', 'rep-table-common'];
    
    function addCell(row, text) {
        var cell = row.insertCell(cellIdx);
        cell.innerHTML = text;
        if ( cell_classes[cellIdx] != '' ) {
            cell.className = cell_classes[cellIdx];
        }
        cellIdx ++;        
    }
    
    var i, table = document.getElementById('rep-divisions');
    deleteTableRows(table);        
    for (i=0; i<json.data.length;i++){
        var json_row = json.data[i];
        var row = table.insertRow(table.rows.length);
        setRowVisProps(row, i);
        cellIdx = 0;
        addCell(row, "<a href=\"javascript: loadTrainers('" + escape(json_row.title) + "', '" + escape(json_row.public_id) + "', " + i + ")\">" + json_row.title + "</a>");
        addCell(row, json_row.tr_number);
        addCell(row, json_row.ja_gwm_involved + '/<span>' + json_row.ja_number + '</span>');
        addCell(row, json_row.ja_avg_bio_age);
        addCell(row, json_row.biol_older_2y);
        addCell(row, json_row.biol_older_1y);
        addCell(row, json_row.biol_equal);
        addCell(row, json_row.biol_younger_1y);
        addCell(row, json_row.biol_younger_2y);
        addCell(row, json_row.qual);
        addCell(row, json_row.ja_gwm_involved_pct);
    }
    document.getElementById(table.id + '-env').style.display = "";
}

function showTrainers(json){
    var cellIdx, cell_classes = ['rep-table-title', 'rep-table-involved', 'rep-table-avg-bio-age', 'rep-table-age-older', 'rep-table-age-older', 'rep-table-common',
        'rep-table-age-younger', 'rep-table-age-younger', 'rep-table-common', 'rep-table-common'];
    
    function addCell(row, text) {
        var cell = row.insertCell(cellIdx);
        cell.innerHTML = text;
        if ( cell_classes[cellIdx] != '' ) {
            cell.className = cell_classes[cellIdx];
        }
        cellIdx ++;
    }
    
    var i, table = document.getElementById('rep-trainers');
    deleteTableRows(table);        
    for (i=0; i<json.data.length;i++){
        var json_row = json.data[i];
        var row = table.insertRow(table.rows.length);
        setRowVisProps(row, i);
        cellIdx = 0;
        addCell(row, "<a href=\"javascript: loadAthletes('" + escape(json_row.public_id) + "', false, " + i + ")\">" + json_row.title + "</a>");
        addCell(row, json_row.ja_gwm_involved + '/<span>' + json_row.ja_number + '</span>');
        addCell(row, json_row.ja_avg_bio_age);
        addCell(row, json_row.biol_older_2y);
        addCell(row, json_row.biol_older_1y);
        addCell(row, json_row.biol_equal);
        addCell(row, json_row.biol_younger_1y);
        addCell(row, json_row.biol_younger_2y);
        addCell(row, json_row.qual);
        addCell(row, json_row.ja_gwm_involved_pct);
    }
    document.getElementById(table.id + '-env').style.display = "";
}

function showAthletes(json){
    var cellIdx, cell_classes = ['rep-table-title', 'rep-table-common', 'rep-table-common', 'rep-table-common', 'rep-table-common', 'rep-table-common',
        'rep-table-common', 'rep-table-common', 'rep-table-common', 'rep-table-common'];
    
    function addCell(row, text) {
        var cell = row.insertCell(cellIdx);
        cell.innerHTML = text;
        if ( cell_classes[cellIdx] != '' ) {
            cell.className = cell_classes[cellIdx];
        }
        cellIdx ++;
        return cell;
    }
    
    var i, table = document.getElementById('rep-athletes'), cell;
    deleteTableRows(table);        
    for (i=0; i<json.data.length;i++){
        var json_row = json.data[i];
        var row = table.insertRow(table.rows.length);
        setRowVisProps(row, i);
        cellIdx = 0;
        addCell(row, json_row.title);
        if ( json_row.involved == "yes" ){
            cell = addCell(row, json_row.age_sign);
            var cls;
            if ( json_row.age_sign == "-" || json_row.age_sign == "!" ) {
                cls = "rep-table-bioage-younger";
                cell.className += " " + cls;
            }
            if ( json_row.age_sign == "+" ) {
                cls = "rep-table-bioage-older";
            } else if ( json_row.age_sign == "-" ) {
                cls = "rep-table-bioage-younger";
            } else {
                cls = "rep-table-bioage-equal";
            }
            addCell(row, '<span class="' + cls + '">' + json_row.bio_age + '</span>/<span class="rep-table-ch-age-small">' + json_row.ch_age + '</span>');
            addCell(row, json_row.tf_months);
            addCell(row, json_row.meas_number);
            addCell(row, json_row.last_meas_date);
            addCell(row, json_row.qual);
            addCell(row, json_row.authorization);
        } else {
            cell = addCell(row, json_row.msg_date);
            cell.colSpan = 2;
//            cell.className = 'rep-table-msg';
            cell = addCell(row, json_row.msg);
            cell.colSpan = 4;
            cell.className = 'rep-table-msg';
            cell = addCell(row, json_row.authorization);
            cell.className = 'rep-table-common';
        }
    }
    document.getElementById(table.id + '-env').style.display = "";
}

function setRowVisProps(row, i) {
    row.style.backgroundColor = rowBgColors[i % 2];
}

function deleteTableRows(table) {
    for(var i=table.rows.length-1; i>0; i--) {
        table.deleteRow(i);
    }
}

function toggleTableRows(table, rowIdx) {
    if ( rowIdx == -1 ) {
        for(var i=table.rows.length-1; i>0; i--) {
            if ( table.rows[i].style.display != '' ) {
                table.rows[i].style.display = '';
            }
        }
        document.getElementById(table.id + '-showall').style.display = (rowIdx==-1?"none":"");
    } else {
        if (table.animHideRows) window.clearInterval(table.animHideRows);
        table.animHideRows = window.setInterval(
            function() { 
                for(var i=table.rows.length-1; i>0; i--) {
                    if ( rowIdx == -1 || rowIdx == i - 1 ) {
                        if ( table.rows[i].style.display != '' ) {
                            table.rows[i].style.display = '';
                            return false;
                        }
                    } else {
                        if ( table.rows[i].style.display != 'none' ) {
                            table.rows[i].style.display = 'none';
                            return false;
                        }
                    }
                }
                window.clearInterval(table.animHideRows);
                document.getElementById(table.id + '-showall').style.display = (rowIdx==-1?"none":"");
                return false;
            } 
            ,5
        );
    }
}

function showAllDivisions(){
    document.getElementById('rep-divisions-showall').style.display = "none";
    document.getElementById('rep-trainers-showall').style.display = "none";
    document.getElementById('rep-trainers-env').style.display = "none";
    document.getElementById('rep-athletes-env').style.display = "none";
    toggleTableRows(document.getElementById('rep-divisions'), -1);
    
}

function showAllTrainers(){
    document.getElementById('rep-athletes-env').style.display = "none";
    toggleTableRows(document.getElementById('rep-trainers'), -1);    
    document.getElementById('rep-trainers-showall').style.display = "none";
}

function onAthletesFilterChange(){
    if ( userGroup == 4 ) {
        loadAthletes(false, true);
    } else {
        loadAthletes(lastTrPublicId, true);
    }
}

function sortHelper() {
    this.directions = [];
    this.NONE = 1;
    this.ASC = 2;
    this.DESC = 3;
    return this;
}

sortHelper.prototype.getColSortDir = function(colIdx){
    var a = this.directions[colIdx];
    return (a?a:this.NONE);
}

sortHelper.prototype.setColSortDir = function(colIdx, sortDir){
    this.directions[colIdx] = sortDir;
}

sortHelper.prototype.toggleColSortDir = function(colIdx){
    var a = this.getColSortDir(colIdx);
    if ( a == this.NONE ) {
        a = this.ASC;
    } else if ( a == this.ASC ) {
        a = this.DESC;
    } else {
        a = this.NONE;
    }
    this.setColSortDir(colIdx, a);
}